﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.Reflection;

namespace sysServices
{
    public partial class eurekaScheduler : ServiceBase
    {
        private System.Timers.Timer myTimer = new System.Timers.Timer();
        public eurekaScheduler()
        {
            InitializeComponent();
            if (!System.Diagnostics.EventLog.SourceExists("eurekaSource"))
            {
                System.Diagnostics.EventLog.CreateEventSource(
                    "eurekaSource", "eurekaLog");
            }
            myEventLog.Source = "eurekaSource";
            myEventLog.Log = "eurekaLog";
        }
        protected override void OnStart(string[] args)
        {
            try
            {
                //Load configuration 

                string execDir = common.fileFuncs.FileNamePath(common.EnvironmentLibs.GetExecutePath());
                common.Settings.sysConfigFile = common.fileFuncs.MakeFileName(execDir, common.Settings.sysConfigFile);
                //common.Consts.constValidCallString = common.Consts.constValidCallMarker;

                myEventLog.WriteEntry("sysConfigFile : " + common.Settings.sysConfigFile);
                application.ConfigLibs.withEncryption = true;
                common.configuration.withEncryption = true;
                application.ConfigLibs.Load_User_Config(false);
                
                myEventLog.WriteEntry("sysScheduleInterval : " + CommonTypes.Settings.sysTimerInterval.ToString());
                myEventLog.WriteEntry("sysNotifyEmailAddress : " + CommonTypes.Settings.sysNotifyEmailAddress.ToString());

                //Setup the timer
                myTimer.Stop();
                myTimer.Interval = CommonTypes.Settings.sysTimerInterval * 1000; // Convert to miliseconds
                myTimer.Enabled = true;
                myTimer.Start();
                myTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent);
            }
            catch (Exception er)
            {
                myEventLog.WriteEntry(er.Message.ToString());
            }
        }
        protected override void OnStop()
        {
            myEventLog.WriteEntry("Stop");
        }

        private void OnTimedEvent(object source, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                postSale.SysLibs.Create_PlanTasks();
                postSale.SysLibs.Notification_IncompletedTask();
            }
            catch (Exception er)
            {
                myEventLog.WriteEntry("Error : " + er.Message);
            }
        }
    }
}
